'''
Created on 2013. 5. 15.

@author: Lee
'''
from google.appengine.api import mail
from google.appengine.ext import ndb
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import Users, UserConfirm
import hashlib
import webapp2

class JoinPage(webapp2.RequestHandler):
    '''
        Join Page
    '''

    def get(self):
        session = get_current_session()
        if session.is_active():
            self.response.write("You're already logged on.")
            return
        
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('join.html')
        
        self.response.write(template.render(template_values))
        
    def post(self):
        session = get_current_session()
        if session.is_active():
            self.response.write("You're already logged on.")
            return
        
        user_email = self.request.POST['user_email']
        user_nick = self.request.POST['user_nickname']
        user_passwd = self.request.POST['passwd']
        user_passwd_cf = self.request.POST['passwd_confirm']
        result_msg = ""

        import re
        if (not user_email) or (not user_nick) or (not user_passwd) or (not user_passwd_cf):
            result_msg = "Form is must fill with information."
        elif not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
            result_msg = "Wrong email format"
        elif user_passwd != user_passwd_cf:
            result_msg = "Wrong password"
        else:
            user_query = Users.query(ndb.OR(Users.user_email == user_email,
                                            Users.user_nickname == user_nick))
            if user_query.count() == 0:
                user = Users()
                user.user_email = user_email
                user.user_nickname = user_nick
                hash_func = hashlib.md5(user_passwd)
                user.user_passwd = hash_func.hexdigest()
                user.user_auth = 0
                user_key = user.put()
                
                user_confirm = UserConfirm()
                user_confirm.user_email = user_email
                user_confirm.hash_key = user_key.urlsafe()
                user_confirm.put()
                
                email_body = '''
                    Dear %s:
                    
                    Your account arrive for certification.
                    
                    If you want to certify your's account, you click the link
                    http://tuna-crew.appspot.com/join/confirm/?key=%s
                    
                    Thank you.
                '''%(user_nick, user_key.urlsafe())
                email_msg = mail.EmailMessage(sender="Taehwa Lee <alghost.lee@gmail.com>",
                                              to=user_email,
                                              subject="TunaCrew: Your account arrive for certification",
                                              body=email_body)
                email_msg.send()
                
                template_values = {}
                template_values['msg'] = '''
                        Join is completed nearly.<br/>
                        <br/>
                        A final step is to certify the account.<br/> 
                        <br/>
                        You have to certify the account.<br/>
                        <br/>
                        Your email: %s<br/>
                    '''%user_email
                template = JINJA_ENVIRONMENT.get_template('result_msg.html')
                
                self.response.write(template.render(template_values))
                return
            
            else:
                result_msg = "Nickname or Email is registered already."
        
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('join.html')
        template_values['error_msg'] = result_msg
        self.response.write(template.render(template_values))


class JoinConfirm(webapp2.RequestHandler):
    '''
        Join Confirm Page
    '''
    
    def get(self):
        session = get_current_session()
        if session.is_active():
            self.response.write("You're already logged on.")
            return
        
        input_hash = self.request.GET['key']
        
        confirm_query = UserConfirm.query(UserConfirm.hash_key==input_hash)
        
        if confirm_query.count() == 0:
            result_type = "Wrong access"
        else:
            confirm_entry = confirm_query.get()
            user_query = Users.query(Users.user_email==confirm_entry.user_email)
            user_entry = user_query.get()
            user_entry.user_auth = 1
            user_entry.put()
            
            template_values = {}
            template = JINJA_ENVIRONMENT.get_template('result_msg.html')
            template_values["msg"] = '''
                Certificaion of your account is completed.
                
                Enjoy TunaCrew
            '''
            self.response.write(template.render(template_values))